package zy.vo.wx;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import zy.entity.wx.product.T_Wx_ProductType;
import zy.util.CommonUtil;

public class WxProductTypeVO {
	public static List<Map<String, Object>> buildLevel(List<T_Wx_ProductType> list){
		List<Map<String, Object>> resultList = new ArrayList<Map<String,Object>>();
		for(T_Wx_ProductType item:list){
			if(CommonUtil.DEFAULT_UPCODE.equals(item.getPt_upcode())){
				Map<String, Object> itemMap = new HashMap<String, Object>();
				itemMap.put("pt_id", item.getPt_id());
				itemMap.put("pt_code", item.getPt_code());
				itemMap.put("pt_upcode", item.getPt_upcode());
				itemMap.put("pt_name", item.getPt_name());
				itemMap.put("subs", new ArrayList<T_Wx_ProductType>());
				resultList.add(itemMap);
			}
		}
		for(T_Wx_ProductType item:list){
			if(CommonUtil.DEFAULT_UPCODE.equals(item.getPt_upcode())){
				continue;
			}
			for(Map<String, Object> itemMap :resultList){
				if(item.getPt_upcode().equals(itemMap.get("pt_code"))){
					((List<T_Wx_ProductType>)itemMap.get("subs")).add(item);
				}
			}
		}
		return resultList;
	}
	
	
	public static String buildTree(List<T_Wx_ProductType> list){
		StringBuffer treeHtml = new StringBuffer();
		treeHtml.append("[{id:0,name:'所有类别',open:true},");
		String nodes="";
		if(list != null && list.size() >0){
			nodes = (initToTree(list,CommonUtil.DEFAULT_UPCODE));
		}
		treeHtml.append(nodes);
		treeHtml.deleteCharAt(treeHtml.length()-1);
		treeHtml.append("]");
		return treeHtml.toString();
	}
	
	public static String initToTree(List<T_Wx_ProductType> list, String rootCode){
		StringBuffer json = new StringBuffer(""); 
		List<T_Wx_ProductType> nodeList = hasChild(list, rootCode); // 获得集合中的父节点下的子集list  mn_IsHaveChildMenuItem
		list.remove(nodeList);
		// 循环子集
		//json.append("{");
		for (T_Wx_ProductType node : nodeList) {
			List<T_Wx_ProductType> Nodes = hasChild(list, node.getPt_code());
			json.append("{id:'" + node.getPt_code() + "',pId:'"+node.getPt_upcode()+"',name:'"+node.getPt_name()+"'");
			if (Nodes.size() > 0) {
				json.append(",open:false");
			}
			json.append("},");
			// 查询全部集合下，是否存在该子集OID的子子集
			if (Nodes.size() > 0) {
				json.append(initToTree(list, node.getPt_code())); // 递归树，传入子子集，子集父节点
			}
		}
		return json.toString();
	}
	
	public static List<T_Wx_ProductType> hasChild(List<T_Wx_ProductType> list, String upcode) {
		  List<T_Wx_ProductType> nodeList = new ArrayList<T_Wx_ProductType>();
		  for (T_Wx_ProductType comm : list) {
		   // 如果数据的父节点==Parent的值，则该数据为子节点，存入list<SysRole>
			   if (comm.getPt_upcode().equals(upcode)) {
				   nodeList.add(comm);
			   }
		  }
		  return nodeList;
	 }
}
